package top.guinguo.advance_04.searcher.util;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.*;
import org.apache.lucene.util.Version;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by guin_guo on 2017/1/3.
 */
public class CustomParserUtil {
    public void searcherByQuery(String value) {
        try {
            IndexSearcher searcher = new IndexSearcher(IndexReader.open(FileIndexUtils.getDirectory()));
            CustomParser parser = new CustomParser(Version.LUCENE_35, "content", new StandardAnalyzer(Version.LUCENE_35));
            Query query = parser.parse(value);
            TopDocs tds;
            tds = searcher.search(query, 50);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (ScoreDoc sd : tds.scoreDocs) {
                Document doc = searcher.doc(sd.doc);
                System.out.println(sd.doc + ":(" + sd.score + ")" +
                        "[" + doc.get("filename") + "]" + "【" + doc.get("path") + "】--->" +
                        doc.get("size") + "----" + sdf.format(new Date(Long.valueOf(doc.get("date"))))
                );
                searcher.close();
            }
        } catch (ParseException e) {
            System.err.println(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
